<?php

namespace app\common\model\jsm;

use think\Model;

class Membersx extends Model {

    protected $connection = ['database' => 'jooj_jsm'];
    protected $table = 'jj_members';
    public $base_table = 'jj_members';

    /**
     * 构造方法，创建不同分表的模型
     * @param int $companyId 集团ID
     */
    public function __construct($companyId = 0) {
         if (!is_array($companyId)) {
            $companyId && $this->table = $this->base_table . '_' . $companyId . 'x';
        }
        $companyId = is_array($companyId) ? $companyId : [];
        parent::__construct($companyId);
    }

    /**
     * 判断表是否存在，不存在就要自动创建
     * @param type $tableName
     * @return boolean
     */
    private function _autoCreateTable() {

        $create_sql = null;
        //try{
        //同时判断这张表存不存在，不存在就要创建
        $create_sql = "CREATE TABLE IF NOT EXISTS ". $this->table . " LIKE " .$this->base_table;
        $result = $this->execute($create_sql);
        if (false === $result) {
            return false;
        } else {
            return true;
        }

//        }catch(\Exception $ex){
//            
//            die("\nSql:".$create_sql."\nMessage:{$ex->getMessage()}\n");
//        }
    }

    private function _getUserInfo($user_info) {
        try {
            $res = $this->where(['unionid' => $user_info['unionId']])->find();
        } catch (\Exception $e) {
            if (strstr($e->getMessage(), 'Base table or view not found')) {
                $res = $this->_autoCreateTable();
                if ($res === false) {
                    die('表建立失败，语句如下：' . $this->getLastSql() . "\n\n");
                } else {
                    $res = $this->_getUserInfo($user_info);
                }
            }
        }
        return $res;
    }
    
    
    /**
     * 根据条件获取粉丝信息
     * @param type $condition
     * @param type $field
     * @return type
     */
    public function getMembersxByCondition($condition,$field='*'){
        return $this->where($condition)->field($field)->find();
    }

    //微信小程序粉丝表创建更新粉丝
    public function create_edit_user($user_info,$scene='') {

        //如果已经存在的会员就更新信息,没有就创建
        if ($this->_getUserInfo($user_info)) {
            $data = [
                'gender' => $user_info['gender'],
                'nickname' => $user_info['nickName'],
                'headimgurl' => $user_info['avatarUrl'],
                'country' => $user_info['country'],
                'province' => $user_info['province'],
                'city' => $user_info['city'],
                'language' => $user_info['language'],
                'last_login_ts' => time(),
                'last_update_ts' => time()
            ];
           $rs =  $this->save($data,['unionid' => $user_info['unionId']]);
        } else {
            $data = [
                'openid' => $user_info['openId'],
                'unionid' => $user_info['unionId'],
                'come_from' => $scene,
                'card_no' => 'xcx_' . uniqid(),
                'gender' => $user_info['gender'],
                'nickname' => $user_info['nickName'],
                'headimgurl' => $user_info['avatarUrl'],
                'country' => $user_info['country'],
                'province' => $user_info['province'],
                'city' => $user_info['city'],
                'language' => $user_info['language'],
                'add_ts' => time(),
                'last_login_ts' => time(),
                'last_update_ts' => time()
            ];
           $rs = $this->insert($data);
        }
        if($rs){
            $rs = 'success';
        }else{
            $rs = 'fail';
        }
        return $rs;
    }

}
